const timeReg = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}";
const titleReg = timeReg + ".*[\\r|\\n]";
const questionNameReg = "^\\s*Q\\d+.*$";
const questionReg = "Q\\d+.*[\\r|\\n]";
const questionNumReg = "^Q\\d+";
const replayQuestionReg = "【.*?】";
const dayjs = require("dayjs");

//克隆对象
export const cloneObj = function (obj) {
  let o;
  if (typeof obj === "object") {
    if (obj === null) {
      o = null;
    } else {
      if (obj instanceof Array) {
        o = [];
        for (var i = 0, len = obj.length; i < len; i++) {
          o.push(cloneObj(obj[i]));
        }
      } else {
        o = {};
        for (var j in obj) {
          o[j] = cloneObj(obj[j]);
        }
      }
    }
  } else {
    o = obj;
  }
  return o;
};

// 拆分每个人的提交
export const splitPerson = function (text) {
  let reg = new RegExp("" + titleReg + "", "g");
  let arr = text.match(reg);
  let arr2 = text.split(reg);
  if (arr2.length === arr.length + 1) {
    arr2 = arr2.splice(1);
  }
  let list = [];
  for (let i = 0, n = arr.length; i < n; i++) {
    let title = arr[i];
    let content = arr2[i];
    let item = readTitle(title);
    list.push({
      ...item,
      title: title,
      content: content,
    });
  }
  return list;
};
// 识别标题
function readTitle(text) {
  let reg = new RegExp(timeReg, "");
  let time = text.match(reg);
  time = time[0];
  let date = time.split(" ")[0];
  let str = text.replace(time, "");
  let qq = new RegExp(/\(\d+\)/).exec(str);
  let email = new RegExp(/<.*>/).exec(str);
  if (qq) {
    str = str.replace(qq, "");
    qq = qq[0].replace("(", "").replace(")", "");
  } else if (email) {
    str = str.replace(email, "");
    email = email[0].replace("<", "").replace(">", "");
  }
  let nickname = str.trim();
  let dayjs = require("dayjs");
  time = dayjs(time).format("YYYY-MM-DD HH:mm:ss");
  // qq = qq.replace('(', '').replace(')', '');
  return {
    time: time,
    date: date,
    qq: qq,
    email: email,
    nickname: nickname,
  };
}
function readText(readerFile) {
  return new Promise((resolve) => {
    if (readerFile) {
      let reader = new FileReader();
      reader.readAsText(readerFile);
      reader.onload = function (e) {
        let result = reader.result;
        resolve(result);
      };
    } else {
      resolve("");
    }
  });
}
// 读取文本文件
export const readFileText = async function (dom) {
  if (typeof dom === "string") {
    dom = document.getElementById(dom);
  }
  let files = dom.files;
  let funs = [];
  for (let i = 0, n = files.length; i < n; i++) {
    let file = files[i];
    funs.push(readText(file));
  }
  let results = await Promise.all(funs);
  let str = "";
  for (let i = 0, n = results.length; i < n; i++) {
    let text = results[i];
    str += text || "";
  }
  return str;
};
// 筛选问题标题
export const splitQuetions = function (str, _questions) {
  if (!str) {
    str = "";
  }
  let arr = str.split(/\r|\n/);
  let reg = new RegExp(questionNameReg, "");
  let questions = [];
  for (let i = 0, n = arr.length; i < n; i++) {
    let s = arr[i];
    if (s.match(reg)) {
      questions.push(s);
    }
  }
  if (_questions && _questions.length > 0) {
    let names = _questions.map((item) => item.name);
    questions = questions.filter((question) => {
      let question2 = question.replace("\n", "").trim();
      let reg2 = new RegExp(questionNumReg, "");
      let arr2 = question2.match(reg2);
      let name = arr2[0];
      return names.includes(name);
    });
  }
  let answers = filterAnswers(str, questions);
  let isFixedAnswer = false;
  for (let i = answers.length - 1; i >= 0; i--) {
    if (answers[i].length < 10) {
      questions.splice(i, 1);
      answers.splice(i, 1);
      isFixedAnswer = true;
    }
  }
  if (isFixedAnswer) {
    answers = filterAnswers(str, questions);
  }
  let obj = {};
  let isHaveRepeat = false;
  let repeatNames = {};
  let list = questions.map((question, i) => {
    question = question.replace("\n", "").trim();
    let reg2 = new RegExp(questionNumReg, "");
    let arr2 = question.match(reg2);
    let name = arr2[0] || "";
    if (obj[name]) {
      obj[name] += 1;
      isHaveRepeat = true;
      repeatNames[name] = 1;
    } else {
      obj[name] = 1;
    }
    let answer = answers[i] || "";
    return {
      name: name,
      question: question,
      answer: answer,
      length: answer.length,
    };
  });
  if (isHaveRepeat) {
    obj = {};
    let spliceIndexs = [];
    for (let i = 0, n = list.length; i < n; i++) {
      let item = list[i];
      if (!repeatNames[item.name]) {
        continue;
      }
      if (obj[item.name] === undefined) {
        obj[item.name] = i;
      } else {
        let index = obj[item.name];
        let item2 = list[index];
        item2.answer += `\n${item.question}\n${item.answer}`;
        item2.length = item2.answer.length;
        list[index] = item2;
        spliceIndexs.push(i);
      }
    }
    for (let i = list.length - 1; i >= 0; i--) {
      if (spliceIndexs.includes(i)) {
        list.splice(i, 1);
      }
    }
  }
  return list;
};
let endTexts = [
  "读书作业请不要在知识星球以及其他互联网渠道发表",
  "《每日问题-S教育学专题读书（第14期）》",
];
export const filterAnswers = function (content, questions) {
  let reg = new RegExp(questions.join("|"), "g");
  let arr = content.split(reg);
  arr = arr.splice(1);
  for (let i = 0, n = arr.length; i < n; i++) {
    let str = arr[i];
    for (let j = 0, m = endTexts.length; j < m; j++) {
      let endText = endTexts[j];
      let index = str.indexOf(endText);
      if (index > -1) {
        str = str.substr(0, index);
        if (str.length < 10) {
          continue;
        }
        arr[i] = str;
        break;
      }
    }
  }
  return arr;
};
// 过滤复盘的题目
export const filterReplayQuestions = function (str, questions) {
  if (questions && questions.length > 0) {
    let answers = filterAnswers(str, questions);
    return questions.map((question, i) => ({
      question: question,
      answer: answers[i],
    }));
  }
  let reg = new RegExp(replayQuestionReg, "g");
  let arr = str.match(reg);
  let arr2 = str.split(reg);
  if (arr2.length === arr.length + 1) {
    arr2 = arr2.splice(1);
  }
  return arr.map((question, i) => ({
    question: question,
    answer: arr2[i],
  }));
};

const openDownloadDialog = (blob, fileName) => {
  // if (typeof url === "object" && url instanceof Blob) {
  //   url = URL.createObjectURL(url); // 创建blob地址
  // }
  // const aLink = document.createElement("a");
  // aLink.href = url;
  // aLink.download = fileName;
  // aLink.click();
  const FileSaver = require("file-saver");
  FileSaver.saveAs(blob, fileName);
};
export const saveDataToFile = (data, fileName, mimeType) => {
  const blob = new Blob([data], { type: mimeType });
  const FileSaver = require("file-saver");
  FileSaver.saveAs(blob, fileName);
  // const url = window.URL.createObjectURL(blob);
  // downloadURL(url, fileName, mimeType);
  // setTimeout(() => {
  //   window.URL.revokeObjectURL(url);
  // }, 1000);
};
// 保存txt
export const saveTXT = function (content, fileName) {
  var blob = new Blob(["\ufeff" + content], { type: "text/txt,charset=UTF-8" });
  openDownloadDialog(blob, fileName);
};
/**
 * 保存CSV文件
 * @params content  csv文件内容
 * @params saveName 保存的文件名
 */
function saveCSV(content, fileName) {
  var blob = new Blob(["\ufeff" + content], { type: "text/csv,charset=UTF-8" });
  openDownloadDialog(blob, fileName);
}
export const exportCSV = function (header, list, fileName) {
  let headText = header.join(",");
  let bodyText = "";
  list.forEach((item) => {
    bodyText = bodyText + "\n" + item.join(",");
  });
  let text = headText + bodyText;
  saveCSV(text, fileName);
};
// 导出文本
export const exportRaw = function (data, name) {
  let urlObject = window.URL || window.webkitURL || window;
  let exportBlob = new Blob([data]);
  let saveLink = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
  saveLink.href = urlObject.createObjectURL(exportBlob);
  saveLink.download = name;
  saveLink.click();
};
// 个位转十位数
export const parseTen = function (num) {
  if (num < 10) {
    return "0" + num;
  }
  return num;
};
// 时间转日期
export const getDateByStr = function (time) {
  let addTime = new Date(time);
  if (!time) {
    addTime = new Date();
  }
  return dayjs(addTime).format("YYYY-MM-DD");
};
export const getTimeByStr = function (time) {
  let addTime = new Date(time);
  if (!time) {
    addTime = new Date();
  }
  return dayjs(addTime).format("HH:mm:ss");
};
export const format2Html = function (str) {
  if (!str) {
    return "";
  }
  str = str.replace(/\n/g, "<br>");
  str = str.replace(/\r/g, "<br>");
  return str;
};
export const trimEmpty = function (str) {
  let index = str.indexOf("\n");
  while (index === 0) {
    str = str.substr(1);
    index = str.indexOf("\n");
  }
  index = str.lastIndexOf("\n");
  while (index === str.length - 1) {
    str = str.substr(0, str.length - 1);
    index = str.lastIndexOf("\n");
  }
  return str;
};
// 复制到剪切板
export const copy2Clipboard = function (text) {
  if (navigator.clipboard) {
    // clipboard api 复制
    navigator.clipboard.writeText(text);
  } else {
    var textarea = document.createElement("textarea");
    document.body.appendChild(textarea);
    // 隐藏此输入框
    textarea.style.position = "fixed";
    textarea.style.clip = "rect(0 0 0 0)";
    textarea.style.top = "10px";
    // 赋值
    textarea.value = text;
    // 选中
    textarea.select();
    // 复制
    document.execCommand("copy", true);
    // 移除输入框
    document.body.removeChild(textarea);
  }
};

// 分析提交时间csv文件
export const readCSV = function (text) {
  let allRows = text.split(/\r?\n|\r/);
  return allRows;
};
